package com.blogSystem.article.controller;

import com.alibaba.fastjson.JSON;
import com.blogSystem.article.client.UserClient;
import com.blogSystem.article.pojo.Article;
import com.blogSystem.article.pojo.User;
import com.blogSystem.article.service.ArticleService;
import com.blogSystem.article.service.CommentService;
import com.blogSystem.article.service.CommentThumbsService;
import com.blogSystem.article.service.ThumbsSerivlce;
import com.blogSystem.article.util.UpLoad;
import com.blogSystem.article.util.UpLoadMore;
import com.fasterxml.jackson.annotation.JsonAlias;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import jnr.ffi.annotations.In;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.Request;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@RestController
@CrossOrigin
@RequestMapping("/edit")
public class EditArticleController {

    @Autowired
    private ArticleService articleService;

@Autowired
private UserClient userClient;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ThumbsSerivlce thumbsSerivlce;

    @Autowired
    private CommentThumbsService commentThumbsService;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/notpass",method = RequestMethod.GET)
    public Result notPass(String _id){
      commentThumbsService.deleteByArticleId(_id);
      thumbsSerivlce.deleteByarticle(_id);
      commentService.deleteByArticleId(_id);
      articleService.deleteById(_id);
      return new Result(true, StatusCode.OK,"删除成功");


    }





    @RequestMapping(value = "/deleteById",method = RequestMethod.POST)
    public Result delete(String _id){
        JwtUtil jwtUtil=new JwtUtil();

      String token= (String) request.getAttribute("token");
       /* if(token!=null&&!"".equals(token)){
            commentThumbsService.deleteByArticleId(_id);
            thumbsSerivlce.deleteByarticle(_id);
            commentService.deleteByArticleId(_id);
            articleService.deleteById(_id);
            return new Result(true, StatusCode.OK,"删除成功");
        }*/




        if(token==null||"".equals(token)){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
        }
       Claims claims=jwtUtil.parseJWT(token);
       String author=claims.getId();
       Article article=articleService.findById(_id);
      String json=userClient.getUserById(article.getAuthor());
      User user= JSON.parseObject(json,User.class);
      article.setAuthorName(user.getUsername());
       if(!author.equals(article.getAuthor())){
           return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
       }


        commentThumbsService.deleteByArticleId(_id);
        thumbsSerivlce.deleteByarticle(_id);
        commentService.deleteByArticleId(_id);
        articleService.deleteById(_id);
        return new Result(true, StatusCode.OK,"删除成功");
    }
    @RequestMapping(value = "/readreview",method = RequestMethod.GET)
    public Result readreview(@RequestParam String _id){
      Article read=articleService.findById(_id);
      String json=userClient.getUserById(read.getAuthor());
      User user=JSON.parseObject(json,User.class);
      read.setAuthorName(user.getUsername());
      return new Result(true,StatusCode.OK,"查询成功！",read);

    }
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(@RequestBody Article article){
      String json=userClient.getUserById(article.getAuthor());
      User user=JSON.parseObject(json,User.class);
      article.setAuthorName(user.getUsername());
        JwtUtil jwtUtil=new JwtUtil();
        String token= (String) request.getAttribute("token");
        if(token==null||"".equals(token)){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
        }

        Claims claims=jwtUtil.parseJWT(token);
      String author=claims.getId();
        Article farticle=articleService.findById(article.get_id());
        if(!author.equals(farticle.getAuthor())){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
        }
        articleService.update(article);
        return new Result(true, StatusCode.OK,"修改成功");
    }
    @RequestMapping(value = "/not_reviewed",method = RequestMethod.POST)
    public Result not_reviewed(@RequestBody Map<String,Integer> pages )
    {
      Integer page=pages.get("page");
     Integer size=pages.get("size");
      Page<Article> articles=articleService.findNotReview(page,size);
        List<Article> list=articles.getContent();
        for(Article article:list){
          System.out.println(article.getAuthor());
          String json=userClient.getUserById(article.getAuthor());
          User user= JSON.parseObject(json,User.class);
          article.setAuthorName(user.getUsername());

        }

        Page<Article> articlePage=new Page<Article>() {
          @Override
          public int getTotalPages() {
            return articles.getTotalPages();
          }

          @Override
          public long getTotalElements() {
            return articles.getTotalElements();
          }

          @Override
          public <U> Page<U> map(Function<? super Article, ? extends U> function) {
            return articles.map(function);
          }

          @Override
          public int getNumber() {
            return articles.getNumber();
          }

          @Override
          public int getSize() {
            return articles.getSize();
          }

          @Override
          public int getNumberOfElements() {
            return articles.getNumberOfElements();
          }

          @Override
          public List<Article> getContent() {
            return list;
          }

          @Override
          public boolean hasContent() {
            return articles.hasContent();
          }

          @Override
          public Sort getSort() {
            return articles.getSort();
          }

          @Override
          public boolean isFirst() {
            return articles.isFirst();
          }

          @Override
          public boolean isLast() {
            return articles.isLast();
          }

          @Override
          public boolean hasNext() {
            return articles.hasNext();
          }

          @Override
          public boolean hasPrevious() {
            return articles.hasPrevious();
          }

          @Override
          public Pageable nextPageable() {
            return articles.nextPageable();
          }

          @Override
          public Pageable previousPageable() {
            return articles.previousPageable();
          }

          @NotNull
          @Override
          public Iterator<Article> iterator() {
            return articles.iterator();
          }
        };

        return new Result(true,StatusCode.OK,"查询成功！",articlePage);
    }
@RequestMapping(value = "/review",method = RequestMethod.GET)
    public Result review(@RequestParam  String _id){
  System.out.println(_id);
    articleService.review(_id);
    return new Result(true, StatusCode.OK, "审核通过！");

}

@RequestMapping(value = "/upload",method = RequestMethod.POST)
  public Result upload(@RequestParam("file") MultipartFile[] uploads){


      if(uploads==null){
        return new Result(true,StatusCode.ERROR, "上传失败！");
      }
  MultipartFile upload=uploads[0];
  UpLoad up=new UpLoad();
  String img=up.upLoadFile(upload,request);
  HttpSession session=request.getSession();
  session.setAttribute("cover",img);
return new Result(true,StatusCode.OK, "上传成功！",img);
}

@RequestMapping(value = "/uploads",method = RequestMethod.POST)

  public Result uploads(@RequestParam("file") MultipartFile[] uploads){
  System.out.println(uploads[0].isEmpty());
  if(uploads[0].isEmpty()){
    return new Result(true,StatusCode.ERROR, "上传失败！");
  }else {
    UpLoadMore upLoadMore = new UpLoadMore();
    List<String> photos = upLoadMore.upLoadFile(uploads, request);
    //HttpSession session=request.getSession();

    return new Result(true, StatusCode.OK, "上传成功！",photos);
  }
}
}
